402. Remove K Digits - LeetCode Solution


Greedy Stack

Python Code:

class Solution:
    def removeKdigits(self, num: str, k: int) -> str:


        stack = []

        for i in range(len(num)):
            while stack and int(stack[-1]) > int(num[i]) and k:
                k-=1
                stack.pop()

            stack.append(num[i])


        while k:
            stack.pop()
            k-=1

        if  len(stack) == 0:
            return "0"
        else:

            a = int("".join(stack))


            return str(a)


Comments

Submit
0 Comments
More Questions

1700B - Palindromic Numbers
702C - Cellular Network
1672C - Unequal Array
1706C - Qpwoeirut And The City
1697A - Parkway Walk
1505B - DMCA
478B - Random Teams
1705C - Mark and His Unfinished Essay
1401C - Mere Array
1613B - Absent Remainder
1536B - Prinzessin der Verurteilung
1699B - Almost Ternary Matrix
1545A - AquaMoon and Strange Sort
538B - Quasi Binary
424A - Squats
1703A - YES or YES
494A - Treasure
48B - Land Lot
835A - Key races
1622C - Set or Decrease
1682A - Palindromic Indices
903C - Boxes Packing
887A - Div 64
755B - PolandBall and Game
808B - Average Sleep Time
1515E - Phoenix and Computers
1552B - Running for Gold
994A - Fingerprints
1221C - Perfect Team
1709C - Recover an RBS